package pixivPc.img;

import pixivPc.http.RequestUtil.SendType;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import pixivPc.http.RequestUtil;

/**
 * 图片
 * 
 * @author wangm
 */
public class Img {

	private final int BUFFER_SIZE = 1024;

	private final String dir;
	private final String name;
	private final String url;
	private final String Referer;

	/**
	 * 图片
	 * 
	 * @param dir
	 *            保存文件夹
	 * @param name
	 *            保存文件名
	 * @param url
	 *            url
	 * @param referer
	 *            跳转源url
	 */
	public Img(String dir, String name, String url, String referer) {
		super();
		this.dir = dir;
		this.name = name;
		this.url = url;
		Referer = referer;
	}

	/**
	 * 下载图片
	 * 
	 * @throws IOException
	 */
	public void download() throws IOException {
		// 打开图片链接
		InputStream inStream = RequestUtil.open(url, SendType.GET, "", Referer);

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();

		int len = 0;
		byte[] buf = new byte[BUFFER_SIZE];
		// read
		while ((len = inStream.read(buf)) != -1) {
			outStream.write(buf, 0, len);
		}
		inStream.close();
		outStream.close();

		// write
		new File(dir).mkdirs();
		File file = new File(dir, name);
		FileOutputStream op = new FileOutputStream(file);
		op.write(outStream.toByteArray());
		op.close();
	}

	/**
	 * 获取下载图片路径
	 * @return 图片路径
	 */
	public String getPath() {
		return dir + File.separator + name;
	}

}
